<template>
	<view class="post-manage">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<input class="search-input" v-model="searchKeyword" placeholder="搜索帖子标题" @input="handleSearch" />
		</view>
		
		<!-- 帖子列表 -->
		<scroll-view class="post-list" scroll-y @scrolltolower="loadMore">
			<view v-if="postList.length > 0">
				<view class="post-item" v-for="(item, index) in postList" :key="index">
					<view class="post-header">
						<image class="user-avatar" :src="item.userInfo.avatar" mode="aspectFill"></image>
						<view class="user-info">
							<text class="username">{{item.userInfo.nickname}}</text>
							<text class="time">{{formatTime(item.createTime)}}</text>
						</view>
					</view>
					<view class="post-content">
						<text class="title">{{item.title}}</text>
						<text class="content">{{item.content}}</text>
						<view class="images" v-if="item.images && item.images.length > 0">
							<image v-for="(img, imgIndex) in item.images" :key="imgIndex" :src="img" mode="aspectFill" @click="previewImage(item.images, imgIndex)"></image>
						</view>
					</view>
					<view class="post-footer">
						<view class="stats">
							<text class="stat-item">
								<text class="iconfont icon-eye"></text>
								<text>{{item.viewCount || 0}}</text>
							</text>
							<text class="stat-item">
								<text class="iconfont icon-like"></text>
								<text>{{item.likeCount || 0}}</text>
							</text>
							<text class="stat-item">
								<text class="iconfont icon-comment"></text>
								<text>{{item.commentCount || 0}}</text>
							</text>
						</view>
						<view class="actions">
							<view class="action-btn edit" @click="editPost(item)">编辑</view>
							<view class="action-btn delete" @click="deletePost(item)">删除</view>
						</view>
					</view>
				</view>
			</view>
			<view v-else class="empty-tip">
				<text>暂无帖子数据</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			searchKeyword: '', // 搜索关键词
			postList: [], // 帖子列表
			page: 1, // 当前页码
			pageSize: 10, // 每页数量
			hasMore: true, // 是否还有更多数据
			isLoading: false // 是否正在加载
		}
	},
	onLoad() {
		this.loadPostList()
	},
	methods: {
		// 加载帖子列表
		async loadPostList(isRefresh = false) {
			if (this.isLoading) return
			
			try {
				this.isLoading = true
				if (isRefresh) {
					this.page = 1
					this.hasMore = true
				}
				
				uni.showLoading({
					title: '加载中...'
				})
				
				const res = await uniCloud.callFunction({
					name: 'getPostList',
					data: {
						page: this.page,
						pageSize: this.pageSize,
						keyword: this.searchKeyword
					}
				})
				
				if (res.result.code === 0) {
					const { list, total } = res.result.data
					
					if (isRefresh) {
						this.postList = list
					} else {
						this.postList = [...this.postList, ...list]
					}
					
					this.hasMore = this.postList.length < total
					this.page++
				} else {
					uni.showToast({
						title: res.result.msg || '加载失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('加载帖子列表失败', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				this.isLoading = false
				uni.hideLoading()
			}
		},
		
		// 搜索处理
		handleSearch() {
			// 防抖处理
			clearTimeout(this.searchTimer)
			this.searchTimer = setTimeout(() => {
				this.loadPostList(true)
			}, 500)
		},
		
		// 加载更多
		loadMore() {
			if (this.hasMore && !this.isLoading) {
				this.loadPostList()
			}
		},
		
		// 编辑帖子
		editPost(post) {
			uni.navigateTo({
				url: `/pages/admin/post/edit?id=${post._id}`
			})
		},
		
		// 删除帖子
		deletePost(post) {
			uni.showModal({
				title: '提示',
				content: '确定要删除这个帖子吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							uni.showLoading({
								title: '删除中...'
							})
							
							// 获取用户信息
							const userInfo = uni.getStorageSync('userInfo')
							console.log('用户信息：', userInfo)
							if (!userInfo.nickname) {
								uni.showToast({
									title: '请先登录',
									icon: 'none'
								})
								return
							}
							console.log(post)
							
							const res = await uniCloud.callFunction({
								name: 'deletePost',
								data: {
									id: post._id,
									userId: userInfo._id
								}
							})
							
							if (res.result.code === 0) {
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								})
								// 重新加载列表
								this.loadPostList(true)
							} else {
								uni.showToast({
									title: res.result.msg || '删除失败',
									icon: 'none'
								})
							}
						} catch (error) {
							console.error('删除帖子失败', error)
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							})
						} finally {
							uni.hideLoading()
						}
					}
				}
			})
		},
		
		// 预览图片
		previewImage(images, current) {
			uni.previewImage({
				urls: images,
				current: current
			})
		},
		
		// 格式化时间
		formatTime(timestamp) {
			const date = new Date(timestamp)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hour = String(date.getHours()).padStart(2, '0')
			const minute = String(date.getMinutes()).padStart(2, '0')
			return `${year}-${month}-${day} ${hour}:${minute}`
		}
	}
}
</script>

<style>
.post-manage {
	min-height: 100vh;
	background-color: #f8f9fc;
}

/* 搜索栏样式 */
.search-bar {
	padding: 20rpx;
	background-color: #fff;
	position: sticky;
	top: 0;
	z-index: 1;
}

.search-input {
	width: 100%;
	height: 80rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
}

/* 帖子列表样式 */
.post-list {
	height: calc(100vh - 100rpx);
	padding: 20rpx;
}

.post-item {
	background-color: #fff;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	padding: 20rpx;
}

.post-header {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.user-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.user-info {
	flex: 1;
}

.username {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	display: block;
}

.time {
	font-size: 24rpx;
	color: #999;
	display: block;
	margin-top: 4rpx;
}

.post-content {
	margin-bottom: 20rpx;
}

.title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 10rpx;
}

.content {
	font-size: 28rpx;
	color: #666;
	display: block;
	margin-bottom: 20rpx;
}

.images {
	display: flex;
	flex-wrap: wrap;
	margin: 0 -5rpx;
}

.images image {
	width: calc(33.33% - 10rpx);
	height: 200rpx;
	margin: 5rpx;
	border-radius: 8rpx;
}

.post-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-top: 20rpx;
	border-top: 1rpx solid #f5f5f5;
}

.stats {
	display: flex;
}

.stat-item {
	display: flex;
	align-items: center;
	margin-right: 30rpx;
	color: #999;
	font-size: 24rpx;
}

.stat-item .iconfont {
	font-size: 28rpx;
	margin-right: 6rpx;
}

.actions {
	display: flex;
}

.action-btn {
	width: 120rpx;
	height: 60rpx;
	line-height: 60rpx;
	text-align: center;
	border-radius: 8rpx;
	font-size: 28rpx;
	margin-left: 20rpx;
}

.action-btn.edit {
	background-color: #4a6ee0;
	color: #fff;
}

.action-btn.delete {
	background-color: #ff4d4f;
	color: #fff;
}

/* 空状态提示 */
.empty-tip {
	text-align: center;
	padding: 100rpx 0;
	color: #999;
	font-size: 28rpx;
}

/* 图标字体 */
@font-face {
	font-family: "iconfont";
	src: url('//at.alicdn.com/t/font_3456789_abcdef.woff2') format('woff2');
}

.iconfont {
	font-family: "iconfont" !important;
	font-style: normal;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

.icon-eye:before {
	content: "\e7ed";
}

.icon-like:before {
	content: "\e7c8";
}

.icon-comment:before {
	content: "\e8e4";
}
</style> 